package com.dy.design_pattern_study.flyweight_pattern.dome2.factory;

import com.dy.design_pattern_study.flyweight_pattern.dome2.Flyweight;
import com.dy.design_pattern_study.flyweight_pattern.dome2.impl.ConcreteFlyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * @CreateBy zhangdingyi
 * @Date 2023-04-23
 * @Content 享元工厂
 * 用来创建并管理Flyweight对象。
 * 它主要是用来确保合理地共享Flyweight，当用户请求一个Flyweight时，
 * FlyweightFactory对象提供一个已创建的实例或者创建一个（如果不存在的话）
 */
public class FlyweightFactory {
    private Map<String, Flyweight> flyweightMap = new HashMap<>();

    public FlyweightFactory() {
        //初始化时，会生成三个实例
        //仅测试专用的实例化
        //实际需要对象时，再去判断对象是否为null来决定是否实例化
        flyweightMap.put("X", new ConcreteFlyweight());
        flyweightMap.put("Y", new ConcreteFlyweight());
        flyweightMap.put("Z", new ConcreteFlyweight());
    }

    //根据客户要求会返回已有的实例
    public Flyweight getFlyweight(String key){
        return flyweightMap.get(key);
    }

}
